package com.gopay.scheduler.job;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.gopay.common.constants.cust.SMSResultConstants;
import com.gopay.common.constants.cust.SMSType;
import com.gopay.common.constants.cust.UserInfoConstants;
import com.gopay.common.cps.dao.wallet.promotions.WaPromotionsLogDao;
import com.gopay.common.cps.dao.wallet.promotions.WaPromotionsParamDao;
import com.gopay.common.domain.UserInfo;
import com.gopay.common.domain.acps.model.AcctMastBean;
import com.gopay.common.domain.cust.CustPersonInfo;
import com.gopay.common.domain.dps.WaPromotionsLog;
import com.gopay.common.domain.dps.WaPromotionsParam;
import com.gopay.common.domain.wallet.promotions.ActivityBounsResult;
import com.gopay.common.domain.wallet.promotions.ActivityBounsVO;
import com.gopay.common.exception.GopayException;
import com.gopay.common.user.dao.CustPersonInfoQueryDAO;
import com.gopay.common.user.dao.UserInfoDAO;
import com.gopay.remote.acps.service.AcctTransRemoteService;
import com.gopay.remote.cps.wallet.promotions.ActivityBounsService;
import com.gopay.remote.user.UserSmsRemoteService;
import com.gopay.remote.vo.UserSendSmsReq;
import com.gopay.scheduler.GopayBaseJob;

/**
 * 注册前1000用户红包发送
 * @author LEI XIAOBAO
 * @date 2015年12月20日
 */
public class RegisterUserBounsWelfareJob extends GopayBaseJob{

	private Logger logger = LoggerFactory.getLogger(RegisterUserBounsWelfareJob.class);

	@Resource(name="waPromotionsLogDAO")
	WaPromotionsLogDao waPromotionsLogDAO;
	
	@Resource(name="commonQueryUserDao")
	UserInfoDAO commonQueryUserDao;
	
	@Resource(name="custPersonInfoQueryDao")
	CustPersonInfoQueryDAO custPersonInfoQueryDao;
	
    @Resource(name = "acctTransRemoteService")
    private AcctTransRemoteService acctTransRemoteService;
	
    @Resource(name="activitBounsClient")
    private ActivityBounsService activitBounsClient;
    
	@Value("#{webProperties['inviteBouns.payCustId']}")
	private String payCustId;
	
	@Value("#{webProperties['inviteBouns.payAcctId']}")
	private String payAcctId;
	
	@Value("#{webProperties['inviteBouns.payUserId']}")
	private String payUserId;
	
	@Resource(name="waPromotionsParamDao")
	private WaPromotionsParamDao waPromotionsParamDao;
	
	@Resource(name = "userSmsRemoteClient")
	private UserSmsRemoteService userSmsRemoteClient;
	
	@Override
	protected void doJobInternal() {
		logger.error("RegisterUserBounsWelfareJob-------------start-----------------");
		int successBounsCount = 0;
		Map<String, Object> queryParams = new HashMap<String, Object>();
		queryParams.put("paramKey", "register_bouns_switch");
		String bounsSwitch = getWaPromotionsParamByParamKey(queryParams);
		logger.error("queryPromotionsParamsByCondition bounsSwitch: "+bounsSwitch);
		if( StringUtils.isNotBlank(bounsSwitch) && bounsSwitch.equals("1") ){	
			//查询payAcctId
			String registerPayAcctId = getWaPromotionsParamKeyByCondition("register_pay_acct_id", payAcctId);
			logger.error("registerPayAcctId: "+registerPayAcctId);
			
			//查询payCustId
			String registerPayCustId = getWaPromotionsParamKeyByCondition("register_pay_cust_id", payCustId);
			logger.error("registerPayCustId: "+registerPayCustId);
			
			//查询payCustId
			String registerPayUserId = getWaPromotionsParamKeyByCondition("register_pay_user_id", payUserId);
			logger.error("registerPayUserId: "+registerPayUserId);
			
			//查询红包数
			String bounsNumber = getWaPromotionsParamKeyByCondition("register_bouns_number", "1000");
			int registerBounsNumber = 1000;
			if( StringUtils.isNotBlank(bounsNumber) ){
				registerBounsNumber = Integer.parseInt(bounsNumber);
			}
			logger.error("registerBounsNumber: "+registerBounsNumber);
			
			//查询红包发送金额
			String bounsAmt = getWaPromotionsParamKeyByCondition("register_bouns_amt", "10.00");
			String registerBounsAmt = "10.00";
			if( StringUtils.isNotBlank(bounsAmt) ){
				registerBounsAmt = bounsAmt;
			}
			logger.error("registerBounsAmt: "+registerBounsAmt);
			
			try {
				WaPromotionsLog waPromotionsLog = waPromotionsLogDAO.getWaPromotionsLogByType("1");
				int regNum = 0;
				if( waPromotionsLog != null &&  StringUtils.isNotBlank(waPromotionsLog.getCustId()) ){
					regNum = Integer.parseInt(waPromotionsLog.getCondition1());
				}
				logger.error("regNum:"+regNum);
				if( regNum >= 0 && regNum < registerBounsNumber ){
					Map<String, Object> params = new HashMap<String, Object>();
					params.put("userType", UserInfoConstants.USER_TYPE_PERSON);
					params.put("userStat", UserInfoConstants.USER_STAT_NORMAL);
					params.put("userResource", "WALLET_APP");
					logger.error("userType: "+ UserInfoConstants.USER_TYPE_PERSON);
					logger.error("userStat: "+ UserInfoConstants.USER_STAT_NORMAL);

					//开始日期
					String startTime = getWaPromotionsParamKeyByCondition("register_bouns_start_time", "");
					logger.error("register_bouns_start_time: "+startTime);
					
					//结束日期
					String endTime = getWaPromotionsParamKeyByCondition("register_bouns_end_time", "");
					logger.error("register_bouns_end_time: "+endTime);
					
					//查询用户数
					List<UserInfo> users = commonQueryUserDao.queryUsersByCreateTs(startTime, endTime);
					if( users != null && users.size() > 0 ){
						logger.error("查询获取到的用户数: "+users.size());
					}
					
					//存放注册用户的手机号，用于短信提醒
					List<String> mobiles = new ArrayList<String>();
					for( UserInfo userInfo : users ){
						WaPromotionsLog waLog = waPromotionsLogDAO.getWaPromotionsLogByType("1");
						if( waLog != null &&  StringUtils.isNotBlank(waLog.getCustId()) ){
							int sendBounsNum = Integer.parseInt(waLog.getCondition1());
							logger.error("已发生注册红包数："+sendBounsNum);
							if( sendBounsNum > registerBounsNumber )continue;
						}
						
						BigDecimal avlAmt = queryBalance(registerPayAcctId, registerPayCustId);
						logger.error("红包账号余额："+avlAmt);
						if( avlAmt.compareTo(new BigDecimal("10.00")) < 0 ) break;
						WaPromotionsLog wpLog = waPromotionsLogDAO.getWaPromotionsLogByCustId(userInfo.getCustId());
						//如果用户已经注册那么跳过
						if( wpLog != null && StringUtils.isNotBlank(wpLog.getType()) 
							&& wpLog.getCustId().equals(userInfo.getCustId()) )continue;
						CustPersonInfo personInfo = custPersonInfoQueryDao.getByCustId(userInfo.getCustId());
						//如果用户不存在不进行发红包操作 
						if( personInfo != null && StringUtils.isNotBlank(personInfo.getCustId()) ){
							ActivityBounsVO activityBounsVO = new ActivityBounsVO();
							//获取账户
							String recvAcctId = getAccounts(personInfo.getCustId());
							logger.error("Call ActivityBounsVO recvAcctId: "+recvAcctId);
							activityBounsVO.setBounsType("1");
							activityBounsVO.setPayAcctId(registerPayAcctId);
							activityBounsVO.setPayCustId(registerPayCustId);
							activityBounsVO.setPayUserId(registerPayUserId);
							activityBounsVO.setTranAmt(registerBounsAmt);
							activityBounsVO.setRecvAcctId(recvAcctId);
							activityBounsVO.setRecvCustId(personInfo.getCustId());
							ActivityBounsResult bounsResult = activitBounsClient.activityBouns(activityBounsVO);
							logger.error("Call ActivityBounsVO return getGopayOrderId: "+bounsResult.getGopayOrderId());
							//发红包成功
							if( StringUtils.isNotBlank(bounsResult.getGopayOrderId()) ){
								successBounsCount++;
								if( regNum > 0 && regNum < 1000 ){
									successBounsCount = 0;
									successBounsCount = regNum+1;
									regNum = 0;
								}
								WaPromotionsLog pLog = new WaPromotionsLog();
								pLog.setGopayOrderId(bounsResult.getGopayOrderId());
								pLog.setType("1");
								pLog.setReward(new BigDecimal(registerBounsAmt));
								pLog.setCreateTime(new Date());
								pLog.setCustId(personInfo.getCustId());
								pLog.setCustMob(personInfo.getCustMob());
								pLog.setCondition1(successBounsCount+"");
								waPromotionsLogDAO.save(pLog);
								mobiles.add(pLog.getCustMob());
								logger.info("第"+successBounsCount+"条callCPS ActivityBounsVO新增成功,orderId: "+bounsResult.getGopayOrderId());
							}
						}
					}
					
					//短信发送
					if( mobiles != null && mobiles.size() > 0 ){
						logger.error("发送短信数: "+mobiles.size());
						logger.error("发送手机号: "+StringUtils.join(mobiles, ","));
						sendSms(mobiles, registerBounsAmt);
					}
				}
			}catch(GopayException ge){
				logger.error("RegisterUserBounsWelfareJob getErrCode: "+ge.getErrCode());
				logger.error("RegisterUserBounsWelfareJob getErrMsg: "+ge.getErrMsg());
			}
			logger.error("新增成功的红包数： "+successBounsCount);
			logger.error("RegisterUserBounsWelfareJob-------------end-------------");
		}
	}

	/**
	 * 获取账户
	 * @param custId
	 * @return
	 */
	private String getAccounts(String custId){
		List<AcctMastBean> list = acctTransRemoteService.getAccounts(custId);
		if (list != null && list.size() == 1) {
			return list.get(0).getAcctId();
		}
		return "";
	}
	
	/**
	 * 查询余额
	 * @return
	 * @throws GopayException
	 */
	public BigDecimal queryBalance(String acctId, String custId) throws GopayException {
		BigDecimal avaAmt = new BigDecimal("0.00");
        try {
            List<AcctMastBean> las = acctTransRemoteService.getAccounts(custId);
            if( las != null && las.size() > 0 ){
                for( AcctMastBean ab:las ){
                    if( StringUtils.equals(ab.getAcctId(), acctId) ){
                        return new BigDecimal(ab.getAvaAmt());
                    }
                }
            }
        } catch (Exception e) {
        	logger.error("DPS查询余额错误: "+e.getMessage());
        }
        return avaAmt;
	}
	
	/**
	 * 短信发送
	 * @param mobiles
	 */
	private void sendSms(List<String> mobiles, String bounsAmt) {
		for (String mob : mobiles) {
			UserSendSmsReq userSmsReq = new UserSendSmsReq();
			userSmsReq.setMobileNo(mob);
			userSmsReq.setContent("您参与手机钱包注册赠红包活动"+bounsAmt+"元已发送至您账户，请登录钱包客户端及时查收。感谢您对钱包产品的鼎力支持。 ");
			userSmsReq.setSmsMaxCount(0);
			userSmsReq.setSmsType(SMSType.OTHER_SMS);
			int result = userSmsRemoteClient.sendMobileSMS(userSmsReq);
			if (SMSResultConstants.SEND_RESULT_FAIL == result) {
				logger.error("send sms error!"+result);
			} else if (SMSResultConstants.SEND_RESULT_EXCEED == result) {
				logger.error("send sms error!"+result);
			}else{
				logger.info("send sms success!"+result);
			}
		}
	}
	
	/**
	 * 
	 * @param param
	 * @return
	 */
	private String getWaPromotionsParamByParamKey(Map<String, Object> param){
		List<WaPromotionsParam> promotionsParams = waPromotionsParamDao.queryPromotionsParamsByCondition(param);
		if( promotionsParams != null && promotionsParams.size() > 0 ){
			WaPromotionsParam waPromotionsParam = promotionsParams.get(0);
			return waPromotionsParam.getParamValue();
		}
		return "";
	}
	
	/**
	 * 
	 * @param condition
	 * @param defaultValue
	 * @return
	 */
	private String getWaPromotionsParamKeyByCondition(String condition, String defaultValue){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("paramKey", condition);
		String paramKey = getWaPromotionsParamByParamKey(params);
		String result = defaultValue;
		if( StringUtils.isNotBlank(paramKey) ){
			result = paramKey;
		}
		return result;
	}
}
